<template>
  <div class="defectOrderDetails h100">
    <editPageNew
      ref="editPage"
      :rightBtnArr="rightBtnArr"
      :stepConfig="stepConfig"
      :moreBtnArr="moreBtnArr"
      boxTitle="抽查记录"
      showStep
      showTopTitle
      :showMore="showMore"
      :creatInfo="formData"
      :closeBox="closeCheckRecord"
    >
      <template slot="editPageTitle">
        <i class="el-icon-document TitleImg"></i>
        缺陷工单 {{ formData.code }}
      </template>
      <template slot="btnDescribe" v-if="formData.autoActiveDate"
        >自动激活时间： {{ formData.autoActiveDate }}</template
      >

      <div class="orderTitle">
        <div class="tipText">
          标题自动生成规则：{设备管理单位名称}{设备名称}{缺陷关键字}
        </div>
        <div v-show="!showInput" class="name">
          <span style="color: red"></span>
          <span class="titleText" :title="orderTitle">{{ orderTitle }}</span>
          <el-link
            v-show="!baseAttachBtn"
            style="font-size: 20px"
            icon="el-icon-edit-outline"
            @click="editTitle"
          ></el-link>
        </div>
        <div v-show="showInput" class="name-input">
          <!--  :class="{remindColor:!userInput}" -->
          <el-input
            type="text"
            v-model="orderTitle"
            @blur="loseFocus"
            @change="userInputTitle"
            placeholder="请输入名称"
            clearable
            ref="mark"
          >
            <template slot="prepend">标题</template>
          </el-input>
        </div>
      </div>
      <el-collapse v-model="activeNames">
        <el-collapse-item name="1">
          <template slot="title">基本信息</template>
          <detailForm
            ref="basicForm"
            :initData="formData"
            :orderStatus="status"
            :pageType="pageType"
            :createByRobot="createByRobot"
            @changeFormData="changeFormData"
            @initUserInput="initUserInput"
            @setOrderTitle="setOrderTitle"
            @setTypeId="setTypeId"
            @setLocation="setLocation"
            @openSelectPatrol="openSelectPatrol"
          ></detailForm>
        </el-collapse-item>
        <div v-if="showWorkFlow || showSubmit">
          <el-collapse-item name="2">
            <template slot="title">流程信息</template>
            <div v-if="formData.origin == 'eam.1.0'">
              数据来源EAM1.0,流程信息无法展示
            </div>
            <workFlow
              v-else
              ref="workFlow"
              :isDetails="pageType == 'query'"
              :currentFlowData="formData"
              @submitSuccess="workFlowSuccess"
              :beforeFlowSubmit="beforeSubmit"
              workflowCode="defect_wait_review"
            ></workFlow>
          </el-collapse-item>
        </div>
        <div v-if="showDispatch">
          <el-collapse-item name="3">
            <template slot="title">派工信息</template>
            <dispatch
              ref="dispatch"
              :formData="formData"
              :pageType="pageType"
              :enableConfig="hasPositionPermission"
              orderType="defect"
              @changeData="changeData"
              @setDispatchData="setDispatchData"
              @setLocation="setLocation"
            />
          </el-collapse-item>
        </div>
        <div v-if="isShowAuxiliaryMaintenance">
          <el-collapse-item name="12">
            <template slot="title">辅助检修工作台</template>
            <AuxiliaryMaintenance :tableData="auxiliaryMaintenanceData" />
            <!-- <AuxiliaryMaintenance :tableData="{}" :tableInfo="{}" /> -->
          </el-collapse-item>
        </div>
        <div v-if="showWorkTicket && haveTicketData">
          <el-collapse-item name="4">
            <template slot="title">工作票信息</template>
            <wokTicketList
              :orderId="formData.id"
              @haveData="(val) => (haveTicketData = val)"
            ></wokTicketList>
          </el-collapse-item>
        </div>
        <div v-if="showWorkTicket && haveServiceData">
          <el-collapse-item name="5">
            <template slot="title">检修申请信息</template>
            <serviceList
              :orderId="formData.code"
              @haveData="(val) => (haveServiceData = val)"
            ></serviceList>
          </el-collapse-item>
        </div>
        <div v-if="showPerform">
          <el-collapse-item name="6">
            <template slot="title">执行信息</template>
            <addPerformItem
              ref="perform"
              :hideBtn="hidePerformBtn"
              :btnJurisdiction="btnJurisdiction"
              :formData="formData"
              :orderId="formData.id"
              :orderStatus="status"
              :pageType="pageType"
              :planTime="planTime"
              orderType="defect"
              @changePerformData="(val) => (havaPerformData = val)"
            ></addPerformItem>
          </el-collapse-item>
        </div>
        <div v-if="showAccept">
          <el-collapse-item name="7">
            <template slot="title">验收信息</template>
            <acceptance
              ref="acceptance"
              :formData="formData"
              :pageType="pageType"
              @changeData="changeData"
              @setAcceptData="setAcceptData"
              orderType="defect"
            />
          </el-collapse-item>
        </div>
        <div v-if="showAnalysisReport">
          <el-collapse-item name="8">
            <template slot="title">分析报告</template>
            <editForm
              :formConfig="analysisConfig"
              ref="analysisForm"
              :formData="analysisData"
            ></editForm>
            <div class="attachConten">
              <div class="attachTitle">附件上传:</div>
              <div class="tebleDiv">
                <attachFormNew
                  style="width: 60%"
                  :disabled="analyAttachBtn"
                  :attachSetting="alalySetting"
                  isDelete
                  multiple
                  ref="attachFile"
                ></attachFormNew>
              </div>
            </div>
          </el-collapse-item>
        </div>
        <div v-if="showDemotionAndPending && demotionData.length > 0">
          <el-collapse-item name="9">
            <template slot="title">降级信息</template>
            <baseTable
              :tableSetting="demotionSetting"
              :tableData="demotionData"
              ref="demotion"
            ></baseTable>
          </el-collapse-item>
        </div>
        <div v-if="showDemotionAndPending && pendingData.length > 0">
          <el-collapse-item name="10">
            <template slot="title">待处理信息</template>
            <baseTable
              :tableSetting="pendingSetting"
              :tableData="pendingData"
              ref="pending"
            ></baseTable>
          </el-collapse-item>
        </div>
        <div v-if="formData.patrolId">
          <el-collapse-item name="11">
            <template slot="title">巡视工单</template>
            <baseTable
              :tableSetting="patrolSetting"
              :tableData="patrolData"
              ref="patrol"
            ></baseTable>
          </el-collapse-item>
        </div>
      </el-collapse>
      <template slot="boxContent">
        <checkRecord
          v-if="showCheckRecord"
          :orderData="formData"
          ref="checkRecord"
        ></checkRecord>
      </template>
    </editPageNew>
    <dialogPublic
      :title="'审核信息'"
      :show.sync="showFlowDialog"
      noFootBtn
      appendTobody
      fullscreen
      @doClose="() => (showFlowDialog = false)"
    >
      <workFlow
        v-if="showFlowDialog"
        :isDetails="pageType == 'query'"
        :currentFlowData="formData"
        @submitSuccess="workFlowSuccess"
        workflowCode="defect_wait_review"
      ></workFlow>
    </dialogPublic>
    <dialogPublic
      :title="'缺陷历史'"
      :show.sync="showHistory"
      @doClose="() => (showHistory = false)"
      appendTobody
      fullscreen
      noFootBtn
    >
      <div class="h100">
        <listTableNew v-bind="tableSetting" ref="klTable"></listTableNew>
      </div>
    </dialogPublic>
    <dialogPublic
      :title="'补录备品备件'"
      :show.sync="showSpareParts"
      @doClose="() => (showSpareParts = false)"
      @doSubmit="doSparePart"
      appendTobody
      fullscreen
    >
      <spareParts ref="spareParts" :exexuteInfo="exexuteInfo"></spareParts>
    </dialogPublic>
    <dialogPublic
      :title="'转派工单'"
      :show.sync="showRedeploy"
      @doClose="() => (showRedeploy = false)"
      @doSubmit="toRedeploy"
      appendTobody
    >
      <div class="h100">
        <editForm
          v-if="showRedeploy"
          :formConfig="redeployConfig"
          ref="redeployForm"
          :formData="redeployData"
        />
      </div>
    </dialogPublic>
    <dialogPublic
      title="关联巡视工单"
      :show.sync="showPatrolOrder"
      @doClose="() => (showPatrolOrder = false)"
      @doSubmit="doSelectPatrol"
      appendTobody
      fullscreen
    >
      <patrolOrder ref="patrolOrder"></patrolOrder>
    </dialogPublic>
    <!-- <checkRecord
      v-if="showCheckRecord"
      :showCheckRecord.sync="showCheckRecord"
      :orderData="formData"
      ref="checkRecord"
    ></checkRecord>-->
  </div>
</template>
<script>
import {
  saveOrUpdate, //新增缺陷工单\保存缺陷工单
  submitApi, //提交缺陷工单
  getDetailsApi, //获取缺陷工单详情
  deleteApi, //删除缺陷工单
  activeApi, //激活缺陷单
  getListNoPageApi, //获取缺陷工单列表，不分页（缺陷历史）
  redeployApi, //转派工单
  saveReportApi, //提交分析报告
  getDefectLevelApi, //获取缺陷等级
  acceptDetailsOrder, //获取分析报告
  saveExecute, //补录备品备件
} from "@/api/orderManagement/defectOrder";
import {
  queryVoList, //不分页查询缺陷工单下缺陷降级信息从表列表
} from "@/api/orderManagement/defectDegradation";
import {
  queryList, //不分页查询缺陷工单下缺陷待处理信息从表列表
} from "@/api/orderManagement/defectPending";
import {
  getOrderDictionApi, //权限
  queryTicketListApi, //根据工单id查询关联的工作票列表
  queryTicketByOrderId, //根据工单id查询关联的工作票
  queryEquipsByOrderId, // 工单关联设备查询接口
} from "@/api/orderManagement/common";
import { getPatrolOrderList } from "@/api/orderManagement/patrolOrder.js";
import detailForm from "./detailForm";
import acceptance from "@/views/orderManagement/publicModule/acceptance";
import addPerformItem from "@/views/orderManagement/publicModule/addItem";
import dispatch from "@/views/orderManagement/publicModule/dispatch";
import checkRecord from "../../checkRecord";
import wokTicketList from "../../wokTicketList";
import serviceList from "../../serviceList";
import spareParts from "./spareParts.vue";
import patrolOrder from "@/views/orderManagement/patrolOrder/replatePage.vue";
import { queryOrderAssetList } from "@/api/standardManagement/orderAsset.js";
import AuxiliaryMaintenance from "@/views/orderManagement/auxiliaryMaintenance/index.vue";
import { sendMessageToQywx } from "@/api/common.js"
export default {
  components: {
    detailForm,
    addPerformItem,
    acceptance,
    dispatch,
    checkRecord,
    wokTicketList, //关联的工作票列表
    serviceList,
    spareParts,
    patrolOrder,
    AuxiliaryMaintenance, // 辅助检修工作台
  },
  data() {
    return {
      hasPositionPermission: false,
      showPrintReview: false,
      showPatrolOrder: false,
      printData: {},
      userInfo: this.$store.getters.userInfo,
      btnJurisdiction: [],
      activeNames: [], //
      editFormData: { status: "" },
      creatInfo: {},
      analysisData: {}, //分析报告数据
      isFirstLevel: false,
      showSpareParts: false,
      exexuteInfo: null,
      createByRobot: false,
      analysisConfig: {
        itemArr: [
          {
            label: "故障现象或故障经过",
            prop: "faultPhenomenon",
            type: "textarea",
            maxlength: "500",
            required: true,
            span: 24,
            rows: 3,
          },
          {
            label: "故障影响",
            prop: "faultImpact",
            type: "textarea",
            maxlength: "500",
            required: true,
            span: 24,
            rows: 3,
          },
          {
            label: "故障检查及处理",
            prop: "faultShooting",
            type: "textarea",
            maxlength: "500",
            required: true,
            span: 24,
            rows: 3,
          },
          {
            label: "故障原因",
            prop: "faultCause",
            type: "textarea",
            maxlength: "500",
            required: true,
            span: 24,
            rows: 3,
          },
          {
            label: "运行维护对策及建议",
            prop: "faultSuggest",
            type: "textarea",
            maxlength: "500",
            required: true,
            span: 24,
            rows: 3,
          },
        ],
      },
      alalySetting: {
        businessId: "", //单据的ID
        businessType: "alalyReport",
      },
      showCheckRecord: false,
      isChangeRouter: false,
      haveTicketData: true,
      haveServiceData: true,
      showInput: false,
      hideBtn: false,
      showRedeploy: false,
      showMore: false,
      showHistory: false,
      showFlowDialog: false,
      showKeyword: false,
      changeType: "",
      parameterList: [],
      chooseData: [],
      tempTableData: [], //临时设备参数表格数据
      moveData: {},
      deptOption: [],
      userOption: [],
      workerList: [],
      demotionData: [],
      demotionSetting: {
        title: "",
        indexShow: true, // 序号显示
        height: 200,
        column: [
          {
            label: "缺陷降级单编号",
            prop: "code",
          },
          {
            label: "缺陷降级单标题",
            prop: "title",
          },
          {
            label: "降级后缺陷等级",
            prop: "newLevel",
            formatter: (row) => {
              let value = row.newLevel;
              return (
                this.$store.getters["fineDirtDataName"](
                  "defect_order_level",
                  value
                ) || value
              );
            },
            width: "120px",
          },
          {
            label: "缺陷降级单状态",
            prop: "status",
            formatter: (row) => {
              let value = row.status;
              return (
                this.$store.getters["fineDirtDataName"](
                  "question_Status",
                  value
                ) || value
              );
            },
            width: "120px",
          },
          {
            label: "当前节点",
            prop: "currNodeName",
            width: "150px",
          },
          {
            label: "创建人",
            prop: "createByName",
            width: "120px",
          },
          {
            label: "创建时间",
            prop: "createTime",
            width: "150px",
          },
        ],
        data: [],
        rowClick: async (row) => {},
      },
      pendingData: [],
      pendingSetting: {
        title: "",
        indexShow: true, // 序号显示
        height: 200,
        column: [
          {
            label: "待处理单编号",
            prop: "code",
          },
          {
            label: "待处理单标题",
            prop: "title",
          },
          {
            label: "预计处理时间",
            prop: "expectProcessTime",
            width: "150px",
          },
          {
            label: "待处理单状态",
            prop: "status",
            formatter: (row) => {
              let value = row.status;
              return (
                this.$store.getters["fineDirtDataName"](
                  "question_Status",
                  value
                ) || value
              );
            },
            width: "120px",
          },
          {
            label: "创建人",
            prop: "createByName",
            width: "120px",
          },
          {
            label: "创建时间",
            prop: "createTime",
            width: "150px",
          },
        ],
        data: [],
        rowClick: async (row) => {},
      },
      patrolData: [],
      patrolSetting: {
        title: "",
        indexShow: true, // 序号显示
        autoHeight: true,
        column: [
          {
            label: "标题",
            prop: "title",
          },
          {
            label: "工单编号",
            prop: "code",
          },
          {
            label: "工单状态",
            prop: "status",
            formatter: (row) => {
              return this.$store.getters["fineDirtDataName"](
                "order_patrol_status",
                row.status
              );
            },
          },
          {
            label: "巡视类别",
            prop: "patrolType",
            formatter: (row) => {
              return this.$store.getters.fineDirtDataName(
                "patrol_way",
                row.patrolType
              );
            },
          },
          {
            label: "所属单位",
            prop: "belongDeptName",
          },
          {
            label: "巡视单位",
            prop: "patrolDeptName",
          },
          {
            label: "巡视人员",
            prop: "patrolDeptName",
            showTooltip: true,
            formatter: (row) => {
              if (row.userPos) {
                return row.userPos.map((item) => item.workerName).join(",");
              } else {
                return "-";
              }
            },
          },
        ],
        data: [],
        rowClick: async (row) => {
          this.goDetailPage(row, "patrolOrderDetails", "edit");
        },
      },
      redeployConfig: {
        itemArr: [
          {
            type: "select",
            label: "缺陷专业",
            prop: "major",
            required: true,
            selectOption: this.$store.getters["dirtData"]("common_major"),
            formatter: (val) => {
              return this.$store.getters["fineDirtDataName"](
                "common_major",
                val
              );
            },
            span: 24,
          },
          {
            label: "责任人",
            prop: "workerName", //多选时，字段要为数组类型
            propArr: "workerArr",
            idsStr: "worker",
            orgStr: "workerType", //是否是外单位，人员类型
            orgNameStr: "workerDeptName",
            orgIdStr: "workerDept",
            multiple: false, //是否多选
            isOutOrg: 0, //是否是外单位
            allowCreate: true, //是否允许创建条目
            option: [], //当前选中的项
            type: "user-select", //类型
            trigger: "change",
            methods: (obj) => {},
            required: true,
            span: 24,
          },
          {
            label: "转派原因",
            prop: "reason",
            type: "textarea",
            maxlength: "500",
            required: true,
            span: 24,
            rows: 6,
          },
        ],
      },
      dispatchData: {},
      havaPerformData: false,
      userInput: false,
      orderTitle: "",
      menuType: "",
      pageType: "",
      status: "",
      formData: {},
      redeployData: {},
      orderStatus: [
        "DRAFT",
        "WAIT_REVIEW",
        "WAIT_DISPATCH",
        "WAIT_EXECUTE",
        "IN_EXECUTE",
        "WAIT_ACCEPT",
        "WAIT_REPORT",
        "ARCHIVED",
      ],
      tableSetting: {
        // selectionShow: true,
        showCustomBtn: false,
        showFilterBtn: false,
        showPagination: false,
        pageConfig: {
          pageCode: "defectOrder-" + this.menuType, //页面标识，用来存储过滤器以及自定义列的时候用
          userId: this.$store.getters.userInfo.id,
        },
        searchObj: {
          searchMethod: (params, sortStr) => {
            this.getHistoryList(params, sortStr);
          },
          queryData: {
            type: "",
            equipmentName: "",
            equipmentId: "",
          },
          searchArr: [
            {
              type: "input",
              label: "编号",
              model: "code",
            },
            {
              type: "input",
              label: "标题",
              model: "title",
            },
            {
              label: "状态",
              model: "statusList",
              type: "select",
              multiple: true,
              option: this.$store.getters["dirtData"]("order_defect_status"),
            },
            {
              label: "设备",
              model: "equipmentName",
              type: "text",
              disabled: true,
            },
          ],
        },
        actionList: [],
        column: [
          {
            label: "编号",
            prop: "code",
            sortable: "custom",
          },
          {
            label: "标题",
            prop: "title",
            sortable: "custom",
            // formatter: row => {
            //   let title =
            //     row.title ||
            //     this.$store.getters.userInfo.orgName +
            //       "-" +
            //       row.equipmentName +
            //       "-" +
            //       row.keys;
            //   return title;
            // }
          },
          {
            label: "设备管理单位",
            id: "deptManage",
            prop: "deptManageName",
            sortable: "custom",
          },
          {
            label: "缺陷关键字",
            prop: "keys",
            sortable: "custom",
          },

          {
            label: "状态",
            prop: "status",
            sortable: "custom",
            formatter: (val) => {
              return this.$store.getters["fineDirtDataName"](
                "order_defect_status",
                val.status
              );
            },
          },
          {
            label: "创建人",
            prop: "createByName",
            sortable: "custom",
          },
          {
            label: "创建时间",
            prop: "createTime",
            textAlign: "center",
            sortable: "custom",
          },
        ],
        //表格方法
        tableMethods: {
          //点击行的方法
          rowClick: (val) => {
            let form = {
              id: val.id,
            };
            let { href } = this.$router.resolve({
              path: "/orderManagement/defectOrder/details",
              query: form,
            });
            window.open(href, "_blank");
          },
        },
      },
      beforeSubmit: {
        //工作流提交前检测
        methods: (data) => {
          if (this.showSubmit) {
            return this.submitBeforeXH(data);
          } else {
            return this.submitBefore(data);
          }
        },
      },
      // 设备类型id
      typeId: "",
      // 辅助检修工作台表格列表数据
      auxiliaryMaintenanceData: {
        // 检修建议
        maintenanceSuggestions: [],
        maintenanceRecords: [],
      },
    };
  },
  computed: {
    rightBtnArr() {
      let arr = [
        {
          text: "保存",
          icon: "el-icon-check",
          hide:
            ["details", "query", "perform"].includes(this.pageType) ||
            [
              "WAIT_EXECUTE",
              "IN_EXECUTE",
              "ARCHIVED",
              "DEPRECATED",
              "PENGDING",
            ].includes(this.status) ||
            (this.status == "WAIT_REVIEW" && !this.reviewCanEdit) ||
            (this.pageType == "add" && this.createByRobot),
          content: this.$utils.getJurisdictionContent(
            this.btnJurisdiction,
            "save",
            this.$store.getters["isBtnAuth"]("save")
          ),
          disabled: !(
            this.hasPositionPermission ||
            this.$store.getters["isBtnAuth"]("save") &&
            this.$utils.getJurisdiction(this.btnJurisdiction, "save")
          ),
          methods: () => {
            this.doSubmit("save");
          },
        },
        {
          text: "提交",
          icon: "el-icon-position",
          hide:
            ["perform", "details", "query"].includes(this.pageType) ||
            [
              "WAIT_DISPATCH",
              "WAIT_REVIEW",
              "WAIT_EXECUTE",
              "IN_EXECUTE",
              "ARCHIVED",
              "DEPRECATED",
              "PENGDING",
            ].includes(this.status) ||
            (localStorage.getItem("currDs") == "water_10" &&
              this.status == "DRAFT"),
          methods: () => {
            if (this.formData.source == "tour"&&!this.formData.patrolId) {
              this.$confirm(`检测到缺陷工单未关联巡视工单，是否继续提交`, "提示", {
                confirmButtonText: "继续",
                cancelButtonText: "前往关联",
                type: "warning",
              })
                .then(() => {
                  this.doSubmit("submit");
                })
                .catch((e) => {
                  this.showPatrolOrder = true;
                });
            } else {
              this.doSubmit("submit");
            }
          },
          content: this.$utils.getJurisdictionContent(
            this.btnJurisdiction,
            "submit",
            this.$store.getters["isBtnAuth"]("submit")
          ),
          disabled: !(
            this.$store.getters["isBtnAuth"]("submit") &&
            this.$utils.getJurisdiction(this.btnJurisdiction, "submit")
          ),
        },
        {
          text: "完成待验收",
          icon: "el-icon-position",
          hide:
            ["perform", "details", "query"].includes(this.pageType) ||
            this.status != "IN_EXECUTE",
          methods: () => {
            this.perform("完成待验收");
          },
          content: this.$utils.getJurisdictionContent(
            this.btnJurisdiction,
            "finishWaitAccept",
            this.$store.getters["isBtnAuth"]("finishWaitAccept")
          ),
          disabled: !(
            this.$store.getters["isBtnAuth"]("finishWaitAccept") &&
            this.$utils.getJurisdiction(
              this.btnJurisdiction,
              "finishWaitAccept"
            )
          ),
        },
        {
          text: "派工",
          icon: "el-icon-position",
          hide:
            ["perform", "details", "query"].includes(this.pageType) ||
            this.status != "WAIT_DISPATCH",
          methods: () => {
            this.doSubmit("submit");
          },
          content: this.$utils.getJurisdictionContent(
            this.btnJurisdiction,
            "dispatch",
            this.$store.getters["isBtnAuth"]("dispatch")
          ),
          disabled: !(
            this.hasPositionPermission ||
            this.$store.getters["isBtnAuth"]("dispatch") &&
            this.$utils.getJurisdiction(this.btnJurisdiction, "dispatch")
          ),
        },
        {
          text: "执行",
          icon: "el-icon-position",
          hide: this.status != "WAIT_EXECUTE",
          content: this.$utils.getJurisdictionContent(
            this.btnJurisdiction,
            "execute",
            this.$store.getters["isBtnAuth"]("execute")
          ),
          disabled: !(
            this.$store.getters["isBtnAuth"]("execute") &&
            this.$utils.getJurisdiction(this.btnJurisdiction, "execute")
          ),

          methods: () => {
            this.perform("执行");
          },
        },
        {
          text: "删除",
          icon: "el-icon-delete",
          hide:
            ["perform", "details", "query"].includes(this.pageType) ||
            this.status != "DRAFT",
          content: this.$utils.getJurisdictionContent(
            this.btnJurisdiction,
            "delete",
            this.$store.getters["isBtnAuth"]("delete")
          ),
          disabled: !(
            this.$store.getters["isBtnAuth"]("delete") &&
            this.$utils.getJurisdiction(this.btnJurisdiction, "delete")
          ),
          methods: () => {
            this.deleteData();
          },
        },
        {
          text: "激活",
          icon: "el-icon-thumb",
          hide: this.status != "PENGDING",
          content: this.$utils.getJurisdictionContent(
            this.btnJurisdiction,
            "activate",
            this.$store.getters["isBtnAuth"]("activate")
          ),
          disabled: !(
            this.$store.getters["isBtnAuth"]("activate") &&
            this.$utils.getJurisdiction(this.btnJurisdiction, "activate")
          ),
          methods: () => {
            this.toActivation();
          },
        },
      ];
      return arr;
    },
    //是否展示提交
    showSubmit() {
      return (
        localStorage.getItem("currDs") == "water_10" && this.status == "DRAFT"
      );
    },
    stepConfig() {
      let obj = {};
      let step = 0;
      if (this.status == "DEPRECATED") {
        obj = {
          nowStep: 0, //当前步骤，对应stepItem数组的下标，例如：0-步骤一、1-步骤二
          stepItem: ["已作废"],
        };
      } else if (this.status == "PENGDING") {
        obj = {
          nowStep: 0, //当前步骤，对应stepItem数组的下标，例如：0-步骤一、1-步骤二
          stepItem: ["待处理"],
        };
      } else {
        step = this.orderStatus.indexOf(this.status);
        obj = {
          nowStep: parseInt(step), //当前步骤，对应stepItem数组的下标，例如：0-步骤一、1-步骤二
          stepItem: [
            "草稿",
            "待审核",
            "待派工",
            "待执行",
            "执行中",
            "待验收",
            "提交分析报告",
            "已归档",
          ],
        };
      }
      return obj;
    },
    moreBtnArr() {
      let arr = [
        {
          text: "办理工作票",
          methods: (item) => {
            this.selectTicketType(item);
          },
          hide: !["WAIT_EXECUTE", "IN_EXECUTE"].includes(this.status),
          isDictionary: true, //是否是数据字典
          child: this.$store.getters["dirtData"]("ticket_work_type"),
          content: this.$utils.getJurisdictionContent(
            this.btnJurisdiction,
            "handleTicketWork",
            this.$store.getters["isBtnAuth"]("handleTicketWork")
          ),
          disabled: !(
            this.$store.getters["isBtnAuth"]("handleTicketWork") &&
            this.$utils.getJurisdiction(
              this.btnJurisdiction,
              "handleTicketWork"
            )
          ),
        },
        {
          text: "检修申请",
          methods: (val) => {
            if (!val) {
              this.toService();
            }
          },
          hide: !["WAIT_EXECUTE", "IN_EXECUTE"].includes(this.status),
          content: this.$utils.getJurisdictionContent(
            this.btnJurisdiction,
            "application",
            this.$store.getters["isBtnAuth"]("application")
          ),
          disabled: !(
            this.$store.getters["isBtnAuth"]("application") &&
            this.$utils.getJurisdiction(this.btnJurisdiction, "application")
          ),
        },
        {
          text: "转派工单",
          methods: (val) => {
            if (!val) {
              this.showRedeploy = true;
            }
          },
          hide: !["WAIT_DISPATCH", "WAIT_EXECUTE", "IN_EXECUTE"].includes(
            this.status
          ),
          content: this.$utils.getJurisdictionContent(
            this.btnJurisdiction,
            "changeDispatch",
            this.$store.getters["isBtnAuth"]("changeDispatch")
          ),
          disabled: !(
            this.$store.getters["isBtnAuth"]("changeDispatch") &&
            this.$utils.getJurisdiction(this.btnJurisdiction, "changeDispatch")
          ),
        },
        {
          text: "申请降级",
          methods: (val) => {
            if (!val) {
              let { id, status, code, level } = this.formData;
              let routerForm = {
                orderId: id,
                orderStatus: status,
                orderCode: code,
                orderLevel: level,
                pageType: "orderAdd",
              };
              this.goToDetails("defectDegradationDetails", routerForm);
            }
          },
          hide: !["WAIT_DISPATCH", "WAIT_EXECUTE", "IN_EXECUTE"].includes(
            this.status
          ),
          content: this.$utils.getJurisdictionContent(
            this.btnJurisdiction,
            "demotion",
            this.$store.getters["isBtnAuth"]("demotion")
          ),
          disabled: !(
            this.$store.getters["isBtnAuth"]("demotion") &&
            this.$utils.getJurisdiction(this.btnJurisdiction, "demotion")
          ),
        },
        {
          text: "申请待处理",
          methods: (val) => {
            if (!val) {
              let { id, status, code } = this.formData;
              let routerForm = {
                orderId: id,
                orderStatus: status,
                orderCode: code,
                pageType: "orderAdd",
              };
              this.goToDetails("defectPendingDetails", routerForm);
            }
          },
          hide: !["WAIT_DISPATCH", "WAIT_EXECUTE", "IN_EXECUTE"].includes(
            this.status
          ),
          content: this.$utils.getJurisdictionContent(
            this.btnJurisdiction,
            "pending",
            this.$store.getters["isBtnAuth"]("pending")
          ),
          disabled: !(
            this.$store.getters["isBtnAuth"]("pending") &&
            this.$utils.getJurisdiction(this.btnJurisdiction, "pending")
          ),
        },
        {
          text: "让步接收",
          methods: (val) => {
            if (!val) {
              let { id, status, code } = this.formData;
              let routerForm = {
                orderId: id,
                pageType: "orderAdd",
              };
              this.goToDetails("concessionAcceptDetails", routerForm);
            }
          },
          hide: this.status != "IN_EXECUTE",
          content: this.$utils.getJurisdictionContent(
            this.btnJurisdiction,
            "concession",
            this.$store.getters["isBtnAuth"]("concession")
          ),
          disabled: !(
            this.$store.getters["isBtnAuth"]("concession") &&
            this.$utils.getJurisdiction(this.btnJurisdiction, "concession")
          ),
        },
        {
          text: "重大问题上报",
          methods: (val) => {
            if (!val) {
              let { id, status, code } = this.formData;
              let routerForm = {
                orderId: id,
                pageType: "orderAdd",
              };
              this.goToDetails("majorIssuesDetails", routerForm);
            }
          },
          hide: this.status != "IN_EXECUTE",
          content: this.$utils.getJurisdictionContent(
            this.btnJurisdiction,
            "question",
            this.$store.getters["isBtnAuth"]("question")
          ),
          disabled: !(
            this.$store.getters["isBtnAuth"]("question") &&
            this.$utils.getJurisdiction(this.btnJurisdiction, "question")
          ),
        },
        {
          text: "工单变更",
          methods: (val) => {
            if (!val) {
              this.toChange();
            }
          },
          hide: !["WAIT_EXECUTE", "IN_EXECUTE"].includes(this.status),
          content: this.$utils.getJurisdictionContent(
            this.btnJurisdiction,
            "orderChange",
            this.$store.getters["isBtnAuth"]("orderChange")
          ),
          disabled: !(
            this.$store.getters["isBtnAuth"]("orderChange") &&
            this.$utils.getJurisdiction(this.btnJurisdiction, "orderChange")
          ),
        },
        {
          text: "备品备件",
          methods: (val) => {
            if (!val) {
              let { id, status, code } = this.formData;
              let routerForm = {
                orderId: id,
                pageType: "orderAdd",
              };
              this.goToDetails("sparePartDetails", routerForm);
            }
          },
          hide: this.status != "WAIT_EXECUTE",
          content: this.$utils.getJurisdictionContent(
            this.btnJurisdiction,
            "spareParts",
            this.$store.getters["isBtnAuth"]("spareParts")
          ),
          disabled: !(
            this.$store.getters["isBtnAuth"]("spareParts") &&
            this.$utils.getJurisdiction(this.btnJurisdiction, "spareParts")
          ),
        },
        {
          text: "缺陷历史",
          methods: () => {
            this.showHistory = true;
            this.getHistoryList();
          },
          hide: ![
            "DRAFT",
            "WAIT_REVIEW",
            "WAIT_DISPATCH",
            "WAIT_EXECUTE",
            "IN_EXECUTE",
          ].includes(this.status),
          content: this.$utils.getJurisdictionContent(
            this.btnJurisdiction,
            "defectHistory",
            this.$store.getters["isBtnAuth"]("defectHistory")
          ),
          disabled: !(
            this.$store.getters["isBtnAuth"]("defectHistory") &&
            this.$utils.getJurisdiction(this.btnJurisdiction, "defectHistory")
          ),
        },
        {
          text: "工单抽查",
          methods: () => {
            this.$refs.editPage.showEditPageBox();
            this.showCheckRecord = true;
          },
          hide: this.status != "ARCHIVED",
          content: this.$utils.getJurisdictionContent(
            this.btnJurisdiction,
            "spotCheck",
            this.$store.getters["isBtnAuth"]("spotCheck")
          ),
          disabled: !(
            this.$store.getters["isBtnAuth"]("spotCheck") &&
            this.$utils.getJurisdiction(this.btnJurisdiction, "spotCheck")
          ),
        },
        {
          text: "导出执行信息",
          methods: () => {
            this.exportExecute();
          },
          hide:
            !["IN_EXECUTE", "WAIT_ACCEPT", "WAIT_REPORT", "ARCHIVED"].includes(
              this.status
            ),
          content: this.$utils.getJurisdictionContent(
            this.btnJurisdiction,
            "exportExecute",
            this.$store.getters["isBtnAuth"]("exportExecute")
          ),
          disabled: !(
            this.$store.getters["isBtnAuth"]("exportExecute") &&
            this.$utils.getJurisdiction(this.btnJurisdiction, "exportExecute")
          ),
        },
        {
          text: "补录备品备件",
          methods: (val) => {
            if (!val) {
              this.supplement();
            }
          },
          hide:
            !["WAIT_ACCEPT", "WAIT_REPORT", "ARCHIVED"].includes(this.status),
          content: this.$utils.getJurisdictionContent(
            this.btnJurisdiction,
            "Supplement",
            this.$store.getters["isBtnAuth"]("Supplement")
          ),
          disabled: !(
            this.$store.getters["isBtnAuth"]("Supplement") &&
            this.$utils.getJurisdiction(this.btnJurisdiction, "Supplement")
          ),
        },
        {
          text: "关联巡视工单",
          methods: () => {
            this.showPatrolOrder = true;
          },
          hide: this.pageType == "add",
          content: this.$utils.getJurisdictionContent(
            this.btnJurisdiction,
            "operateRecord",
            this.$store.getters["isBtnAuth"]("operateRecord")
          ),
          disabled: !(
            this.$store.getters["isBtnAuth"]("operateRecord") &&
            this.$utils.getJurisdiction(this.btnJurisdiction, "operateRecord")
          ),
        },
        {
          text: "操作记录",
          methods: () => {
            this.$refs.editPage.showOperate();
          },
          hide: this.status == "",
          content: this.$utils.getJurisdictionContent(
            this.btnJurisdiction,
            "operateRecord",
            this.$store.getters["isBtnAuth"]("operateRecord")
          ),
          disabled: !(
            this.$store.getters["isBtnAuth"]("operateRecord") &&
            this.$utils.getJurisdiction(this.btnJurisdiction, "operateRecord")
          ),
        },
        {
          text: "打印预览",
          methods: () => {
            this.toPrint();
          },
          hide: this.status != "ARCHIVED",
          content: this.$utils.getJurisdictionContent(
            this.btnJurisdiction,
            "print",
            this.$store.getters["isBtnAuth"]("print")
          ),
          disabled: !(
            this.$store.getters["isBtnAuth"]("print") &&
            this.$utils.getJurisdiction(this.btnJurisdiction, "print")
          ),
        },
      ];
      return arr;
    },
    showDispatch() {
      let status = this.status;
      //派工信息
      return (
        [
          "WAIT_DISPATCH",
          "WAIT_EXECUTE",
          "IN_EXECUTE",
          "ARCHIVED",
          "WAIT_ACCEPT",
          "WAIT_REPORT",
          "PENGDING",
          "DEPRECATED",
        ].includes(this.status) && this.pageType != "add"
      );
    },
    showWorkFlow() {
      return (
        [
          "WAIT_REVIEW",
          "WAIT_DISPATCH",
          "WAIT_EXECUTE",
          "IN_EXECUTE",
          "ARCHIVED",
          "WAIT_ACCEPT",
          "WAIT_REPORT",
          "PENGDING",
          "DEPRECATED",
        ].includes(this.status) && this.pageType != "add"
      );
    },
    showPerform() {
      //执行信息
      return (
        [
          "IN_EXECUTE",
          "ARCHIVED",
          "WAIT_ACCEPT",
          "WAIT_REPORT",
          "DEPRECATED",
        ].includes(this.status) && this.pageType != "add"
      );
    },
    reviewCanEdit() {
      let { currNodeName, currNodeUser, status } = this.formData;
      if (currNodeUser) {
        let userArr = currNodeUser.split(",");
        return (
          currNodeName == "设备管理单位领导审核" &&
          userArr.includes(this.userInfo.name) &&
          status == "WAIT_REVIEW"
        );
      } else {
        return false;
      }
    },
    showAccept() {
      //验收信息
      return (
        ["ARCHIVED", "WAIT_ACCEPT", "WAIT_REPORT", "DEPRECATED"].includes(
          this.status
        ) && this.pageType != "add"
      );
    },
    showAnalysisReport() {
      //验收信息
      return (
        ["ARCHIVED", "WAIT_REPORT", "DEPRECATED"].includes(this.status) &&
        this.pageType != "add"
      );
    },
    showFlow() {
      return [
        "WAIT_REVIEW",
        "WAIT_DISPATCH",
        "WAIT_EXECUTE",
        "IN_EXECUTE",
        "WAIT_ACCEPT",
        "WAIT_REPORT",
        "ARCHIVED",
        "PENGDING",
      ].includes(this.status);
    },
    baseAttachBtn() {
      if (
        (["DRAFT", undefined, null, ""].includes(this.status) &&
          this.pageType == "edit") ||
        (this.status == "WAIT_REVIEW" && this.reviewCanEdit) ||
        this.pageType == "add"
      ) {
        return false;
      } else {
        return true;
      }
    },
    hidePerformBtn() {
      if (this.status == "IN_EXECUTE" && this.pageType == "edit") {
        return false;
      } else {
        return true;
      }
    },
    planTime() {
      let { endTime, startTime } = this.dispatchData;
      return {
        endTime,
        startTime,
      };
    },
    showDemotionAndPending() {
      return [
        "IN_EXECUTE",
        "WAIT_ACCEPT",
        "ARCHIVED",
        "PENGDING",
        "WAIT_REPORT",
        "DEPRECATED",
      ].includes(this.status);
    },
    // 辅助检修工作台
    isShowAuxiliaryMaintenance() {
      // auxiliaryMaintenanceData所有的表单数据都获取到才渲染辅助检修工作台
      let list = Object.entries(this.auxiliaryMaintenanceData);
      let flag = list.every((i) => i[1].length);
      return (
        flag &&
        ["WAIT_DISPATCH", "PENGDING", "IN_EXECUTE", "WAIT_ACCEPT"].includes(
          this.status
        )
      );
    },
    showWorkTicket() {
      return [
        "WAIT_EXECUTE",
        "IN_EXECUTE",
        "WAIT_ACCEPT",
        "ARCHIVED",
        "PENGDING",
        "WAIT_REPORT",
        "DEPRECATED",
      ].includes(this.status);
    },
    analyAttachBtn() {
      return this.status != "WAIT_REPORT";
    },
  },
  watch: {
    activeNames: {
      handler(val) {
        let item = val[val.length - 1];
        if (item == "1") {
          let name = this.formData.equipmentName || "";
        } else if (["3", "6"].includes(item)) {
          //待派工
          this.$nextTick(() => {
            this.$refs.dispatch.getDataJudge();
          });
        } else if (item == "7") {
          //待验收
          this.$nextTick(() => {
            this.$refs.acceptance.getDataJudge();
          });
        }
      },
      deep: true,
    },
    status: {
      handler(val) {
        this.formData.status = val;
        this.unfoldMethod();
        //获取权限
        this.jurisdiction();
        //获取缺陷降级跟待处理数据
        if (
          [
            "IN_EXECUTE",
            "WAIT_ACCEPT",
            "ARCHIVED",
            "PENGDING",
            "DEPRECATED",
            "WAIT_REPORT",
          ].includes(val)
        ) {
          this.getDemotionData();
          this.getPendingData();
        }
        if (val == "") {
          this.showMore = false;
        } else {
          this.showMore = true;
        }
        /* 初始化分析报告表单 */
        let itemArr = [];
        $.extend(true, itemArr, this.analysisConfig.itemArr);
        itemArr.map((i) => {
          if (val == "WAIT_REPORT") {
            i.disabled = false;
          } else {
            i.disabled = true;
          }
        });
        this.analysisConfig.itemArr = itemArr;
        if (val == "WAIT_REPORT") {
          this.getDefectLevel();
        }
      },
    },
    typeId(newVal) {
      if (newVal) {
        const queryData = {
          page: 1,
          pageSize: 50,
          sort: 1,
          typeId: this.typeId,
        };
        // 查询检修建议
        queryOrderAssetList(queryData).then((res) => {
          this.auxiliaryMaintenanceData.maintenanceSuggestions = res.data.list;
        });
      }
    },
    "formData.equipmentId": {
      handler: function (newVal) {
        console.log("equipmentId", newVal);
        if (newVal) {
          // 查询检修记录
          queryEquipsByOrderId({ equipmentId: newVal }).then((res) => {
            this.auxiliaryMaintenanceData.maintenanceRecords = res.data;
          });
        }
      },
    },
  },
  async created() {
    let appId = this.$store.getters.currentAppInfo.appId;
    this.hasPositionPermission = await this.$utils.isPosition(
      localStorage.getItem('currLeader') || '',
      "维修部门负责人",
      appId
    )
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      let {
        id,
        pageType,
        menuType,
        idInspectResultLog,
        source,
        discovereTime,
        desc,
      } = this.$route.query;
      this.pageType = pageType;
      this.menuType = menuType;
      this.alalySetting.businessId = id;
      if (id) {
        //非新增
        this.formData.id = id;
        //判断页面类型
        let haveJurisdiction = this.$store.getters["isBtnAuth"]("edit");
        this.pageType = haveJurisdiction ? "edit" : "detail";
        this.showInput = false;
        if (this.$refs.basicForm) {
          this.$refs.basicForm.getDetails(this.formData.id);
        }
      } else {
        //新增
        this.showInput = true;
        this.activeNames = ["1"];
        this.formData.type = this.menuType;
        this.formData.findTime = this.$utils.getCurrentDate("minutes");
        this.formData.keys = "无";
        this.formData.level = "threeclass";
        this.formData.source = "tour";
        //初始化发现人
        let { name, id, isOutOrg } = this.userInfo;
        this.formData.finderName = name;
        this.formData.finder = id;
        this.formData.finderNameArr = id;
        if (idInspectResultLog) {
          this.formData.source = source;
          this.formData.findTime = discovereTime;
          this.formData.desc = desc;
          this.formData.idInspectResultLog = idInspectResultLog;
          this.createByRobot = true;
        }
      }
    },
    //获取页面权限
    jurisdiction() {
      let form = {
        orderId: this.formData.id,
        orderStatus: this.status,
        orderType: "defect",
      };
      getOrderDictionApi(form).then((res) => {
        let data = res.data;
        if (Array.isArray(data)) {
          this.btnJurisdiction = data;
        } else {
          this.btnJurisdiction = [];
        }
        let postList = this.$store.getters.userInfo.postUserVoList;
        let hasPost = postList.find((item) => {
          return item.postName == "仓库管理员";
        });
        if (hasPost) {
          this.btnJurisdiction.push({
            code: "Supplement",
            jurisdiction: true,
            rule: "只有以下人员有权限：仓库管理员",
          });
        } else {
          this.btnJurisdiction.push({
            code: "Supplement",
            jurisdiction: false,
            rule: "只有以下人员有权限：仓库管理员",
          });
        }
        this.changePageType();
      });
    },
    //获取设备安装位置
    setLocation(obj) {
      if (this.status == "WAIT_DISPATCH") {
        this.$refs.dispatch.setLocation(obj);
      }
    },
    //选择巡视工单
    async doSelectPatrol() {
      let data = this.$refs.patrolOrder.getSelectData();
      this.$set(this.formData, "patrolId", data.id);
      this.showPatrolOrder = false;
      let params = {
        id: this.formData.id,
        patrolId: data.id,
      };
      saveOrUpdate(params).then((res) => {
        this.$refs.basicForm.getDetails(res.data.id);
      });
    },
    /* 结合角色权限，对页面是否可编辑进行控制 */
    changePageType() {
      let status = this.status || "";
      //用户角色权限
      let userJurisdiction = this.$store.getters["isBtnAuth"]("edit");
      //业务控制权限
      let businessJurisdiction = this.$utils.getJurisdiction(
        this.btnJurisdiction,
        "save"
      );
      let haveJurisdiction = userJurisdiction && businessJurisdiction;
      //确定pageType类型
      this.pageType = haveJurisdiction ? "edit" : "detail";
    },
    //折叠与展开
    unfoldMethod() {
      let status = this.status;
      if (["DRAFT"].includes(status)) {
        //草稿
        if (this.showSubmit) {
          this.activeNames = ["1", "2", "11"];
        } else {
          this.activeNames = ["1", "11"];
        }
      } else if (status == "WAIT_REVIEW") {
        this.activeNames = ["1", "2"];
      }
      if (["WAIT_DISPATCH"].includes(status)) {
        //待派工、待执行
        this.activeNames = ["3"];
      } else if (status == "WAIT_EXECUTE") {
        //待执行
        this.activeNames = ["3", "4"];
      } else if (status == "DEPRECATED") {
        //废弃
        this.activeNames = ["1"];
      } else if (status == "PENGDING") {
        //待处理
        this.activeNames = ["1", "10"];
      } else if (status == "IN_EXECUTE") {
        //执行中
        this.activeNames = ["4", "6"];
      } else if (status == "WAIT_ACCEPT") {
        //验收
        this.activeNames = ["7"];
      } else if (status == "WAIT_REPORT") {
        //提交分析报告
        this.activeNames = ["8"];
      } else if (status == "ARCHIVED") {
        this.activeNames = [];
      }
    },
    //获取缺陷降级的数据
    getDemotionData() {
      let form = {
        defectId: this.formData.id,
      };
      queryVoList(form).then((res) => {
        let data = res.data || [];
        this.demotionData = data;
        setTimeout(() => {
          if (data.length > 0) {
            this.$refs.demotion.setTableData(data);
          }
        }, 100);
      });
    },
    openSelectPatrol() {
      this.showPatrolOrder = true;
    },
    //获取待处理的数据
    getPendingData() {
      let form = {
        defectId: this.formData.id,
      };
      queryList(form).then((res) => {
        let data = res.data || [];
        this.pendingData = data;
        setTimeout(() => {
          if (data.length > 0) {
            this.$refs.pending.setTableData(data);
          }
        }, 100);
      });
    },
    async doSubmit(type) {
      let status = this.status;
      let data = {};
      //基本信息的保存
      if (
        ["DRAFT", "WAIT_REVIEW"].includes(status) ||
        (this.pageType == "add" && ["", null, undefined].includes(status))
      ) {
        //新增或者草稿状态时，保存缺陷-基本信息，提交缺陷-基本信息
        let hasFile = true;
        if (this.orderTitle) {
          if (type == "submit") {
            data = await this.$refs.basicForm.getFormData();
            hasFile = this.$refs.basicForm.haveAttachFile();
          } else {
            //保存时不做校验
            data = await this.$refs.basicForm.getFormData(false);
          }
          if (hasFile || this.createByRobot) {
            data.title = this.orderTitle;
            data.isCommit = false;
            delete data.finderNameArr;
            if (type == "submit") {
              this.$confirm(`提交后数据将会自动保存，是否继续`, "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
              })
                .then(() => {
                  this.submitOrder(data, type);
                })
                .catch((e) => {});
            } else {
              this.submitOrder(data, type);
            }
          } else {
            this.$message.warning("请上传现场照片!");
          }
        } else {
          this.$message.warning("请填写标题!");
        }
      } else if (status == "WAIT_DISPATCH") {
        //待派工状态时，保存缺陷-派工信息，提交缺陷-派工信息
        this.$refs.dispatch.saveData(type);
      } else if (status == "WAIT_ACCEPT") {
        //验收状态时，保存缺陷-验收信息，提交缺陷-验收信息
        let sendMessageParam = {
          title: this.formData.title,
          handler: this.formData.createBy
        }
        // 发送短信
        await sendMessageToQywx(sendMessageParam)
        this.$refs.acceptance.saveData(type);
      } else if (status == "WAIT_REPORT") {
        //分析报告
        this.$refs.attachFile.doSubmitFiles("detail");
        this.saveReport(type);
      }
    },
    //判断缺陷等级
    getDefectLevel() {
      getDefectLevelApi(this.formData.level).then((res) => {
        this.isFirstLevel = res.data;
        this.changeAnalyRules();
      });
    },
    //修改分析报告表单的必填项
    changeAnalyRules() {
      let itemArr = this.analysisConfig.itemArr;
      let rules = {};
      itemArr.map((i) => {
        rules[i.prop] = [];
        let itemRules = {};
        if (this.isFirstLevel) {
          //是一级分类
          itemRules = {
            required: true,
            message: "请输入" + i.label,
            trigger: i.trigger || "blur",
          };
        }
        rules[i.prop].push(itemRules);
      });
      this.$refs.analysisForm.setItemArrRules(rules);
    },
    //提交分析报告
    saveReport(type) {
      this.$refs.analysisForm.getFormData().then((data) => {
        let { id, orderId, orderType } = this.analysisData;
        data.isCommit = type == "save" ? false : true;
        data.orderId = orderId;
        data.orderType = orderType;
        data.id = id;
        saveReportApi(data).then((res) => {
          if (type == "submit") {
            this.changeData();
          } else {
            this.$refs.acceptance.getAcceptDetails();
          }
        });
      });
    },
    //获取分析报告数据
    setAcceptData(data) {
      let {
        id,
        orderId,
        orderType,
        faultCause,
        faultImpact,
        faultPhenomenon,
        faultShooting,
        faultSuggest,
      } = data;
      this.analysisData = {
        id,
        orderId,
        orderType,
        faultCause,
        faultImpact,
        faultPhenomenon,
        faultShooting,
        faultSuggest,
      };

      // acceptDetailsOrder(this.formData.id).then(res => {
      //   let data = res.data || {};
      //   if (JSON.stringify(data) != "{}") {
      //   }
      // });
    },
    submitOrder(data, type) {
      let status = this.status || "";
      saveOrUpdate(data).then(async (res) => {
        //保存了之后要返回表单信息，流程启动要用到code
        this.$utils.updateStorage();
        this.$message.success("操作成功！");
        await this.$refs.basicForm.setAttachId(res.data.id, this.pageType);
        if (this.pageType == "add") {
          this.pageType = "edit";
          this.formData = res.data;
          this.status = res.data.status;
          if (type == "submit") {
            this.$utils.addOperateLog(this.formData.id, "新增并提交-缺陷工单");
            this.$refs.basicForm.getDetails(res.data.id);
            this.isChangeRouter = true;
            this.showFlowDialog = true;
          } else {
            this.$utils.addOperateLog(this.formData.id, "新增-缺陷工单");
            //this.changeRouter();
          }
        } else if (status == "DRAFT" && type == "submit") {
          this.$utils.addOperateLog(this.formData.id, "修改并提交-缺陷工单");
          this.showFlowDialog = true;
          this.$refs.basicForm.getDetails(res.data.id);
        } else {
          this.$utils.addOperateLog(this.formData.id, "修改-缺陷工单");
          this.$refs.basicForm.getDetails(res.data.id);
        }
      });
    },
    //执行
    async perform(operationName) {
      try {
        //验证是否可以提交
        let status = this.formData.status || "";
        let account = this.userInfo.id;
        let index = this.orderStatus.indexOf(this.status);
        let form = {
          orderId: this.formData.id,
          status: this.orderStatus[index + 1],
        };
        if (
          this.status == "WAIT_EXECUTE" ||
          (this.status == "IN_EXECUTE" && this.havaPerformData)
        ) {
          let message = "";
          let res = await queryTicketByOrderId(this.formData.id);
          let workStatus = res.data || [];
          if (workStatus.length > 0) {
            //有关联工作票
            let arr = [];
            if (this.status == "WAIT_EXECUTE") {
              arr = [1, 2, 3, 4, 5];
            } else {
              arr = [1, 2, 3, 4, 5, 6, 7];
            }
            //取交集
            let intersection = workStatus.filter((val) => {
              return arr.indexOf(val) > -1;
            });
            if (intersection.length > 0) {
              //有交集
              if (this.status == "IN_EXECUTE") {
                message = "未归档";
              } else {
                message = "未许可";
              }
            }
            if (message) {
              this.$confirm(`当前存在${message}的工作票，是否继续?`, "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
              })
                .then(() => {
                  if (this.status == "IN_EXECUTE") {
                    this.$refs.perform.getAttachList();
                  }
                  this.performOrder(form, status, operationName);
                })
                .catch((e) => {});
            } else {
              // if (this.status == "IN_EXECUTE") {
              //   this.$refs.perform.getAttachList();
              // }
              this.performOrder(form, this.status, operationName);
            }
          } else {
            //没有关联工作票
            if (this.status == "IN_EXECUTE") {
              this.$refs.perform.getAttachList();
            }
            this.performOrder(form, status, operationName);
          }
        } else {
          //没有关联工作票
          this.$message.warning("执行信息尚未保存，请先保存执行信息再提交");
        }
      } catch (error) {}
    },
    performOrder(form, status, operationName) {
      let sendMessageParam = {}
      if(operationName === '执行') {
        sendMessageParam = {
          title: this.formData.title,
          handler: this.dispatchData.worker || this.dispatchData.trackPersonId
        }
      }
      if(operationName === '完成待验收') {
        sendMessageParam = {
          title: this.formData.title,
          handler: this.formData.createBy
        }
      }
      // 发送消息
      sendMessageToQywx(sendMessageParam).then(() => {
        submitApi(form).then((res) => {
            this.$utils.updateStorage();
            this.$message.success("操作成功");
            this.$utils.addOperateLog(
              this.formData.id,
              `${operationName}-缺陷工单`
            );
            this.changeData();
        });
      })
    },
    //激活
    toActivation() {
      activeApi(this.formData.id).then((res) => {
        this.$message.success("操作成功");
        this.$utils.addOperateLog(this.formData.id, "激活-缺陷工单");
        this.$refs.basicForm.getDetails(); //获取详情
      });
    },
    //转派工单
    async toRedeploy() {
      this.showRedeploy = false;
      let data = await this.$refs.redeployForm.getFormData();
      if (this.status == "WAIT_DISPATCH") {
        data.dispatch = false;
      } else {
        data.dispatch = true;
      }
      data.preMajor = this.formData.major;
      data.orderId = this.formData.id;
      data.orderType = "defect";
      data.workerType = this.$utils.changeUserType(data.workerType);
      redeployApi(data).then((res) => {
        this.$message.success("操作成功");
        this.$utils.addOperateLog(
          this.formData.id,
          `转派给:${data.workerDeptName} ${data.workerName}`
        );
        this.$refs.basicForm.getDetails(this.formData.id);
        if (this.status == "WAIT_DISPATCH") {
          setTimeout(() => {
            this.jurisdiction();
          }, 200);
        }
      });
    },
    //数据变更
    changeData() {
      this.$refs.basicForm.getDetails(); //获取详情
    },
    setDispatchData(data) {
      this.dispatchData = data;
    },
    changeRouter() {
      /* 修改路由参数 */
      let obj = JSON.parse(JSON.stringify(this.$router.currentRoute.query));
      obj = Object.assign(obj, {
        id: this.formData.id,
        pageType: "edit",
        status: this.formData.status,
      });
      this.$router.push({
        query: obj,
      });
    },

    //删除
    deleteData() {
      //对数据来源进行判断
      this.$confirm(`是否确认删除`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteApi(this.formData.id).then((res) => {
            this.$utils.updateStorage();
            this.$message.success("操作成功");
            //删除相应的附件
            //this.$refs.attachFile.deleteTypeFiles();
            this.$refs.editPage.closePage();
          });
        })
        .catch((e) => {});
    },
    //提交前检测
    async submitBefore(data) {
      //如果是起草节点;设备管理单位领导审核时，可修改基本信息
      return new Promise((resolve, reject) => {
        const currDs = localStorage.getItem('currDs')
        // 待审批节点 提示是否传阅
        if(currDs === 'water_06' && this.status == 'WAIT_REVIEW' && data.operation == '32') {
          this.$confirm('工单是否需要传阅给其他人？', '提示', {
            distinguishCancelAndClose: true,
            confirmButtonText: '直接提交',
            cancelButtonText: '需要传阅',
            type: 'info'
          }).then(() => {
            if (
              (this.formData.currNodeName && this.status == "DRAFT") ||
              this.reviewCanEdit
            ) {
              let hasFile = this.$refs.basicForm.haveAttachFile();
              if (hasFile || this.createByRobot) {
                this.$refs.basicForm
                  .getFormData()
                  .then((formData) => {
                    formData.title = this.orderTitle;
                    formData.isCommit = false;
                    saveOrUpdate(formData)
                      .then((res) => {
                        resolve(true);
                      })
                      .catch((e) => {
                        reject(e);
                      });
                  })
                  .catch((e) => {
                    if (this.reviewCanEdit && e == "未填写完整") {
                      this.$message.warning("请将“基本信息”填写完整！");
                    }
                    reject(e);
                  });
              } else {
                this.$message.warning("请上传现场照片!");
              }
            } else {
              resolve(true);
            }
          }).catch((action) => {
            action === 'cancel' && this.$refs.editPage.modifyShareFromParent(() => {
              // this.submitBefore(data)
            })
          })

          return
        }

        if (
          (this.formData.currNodeName && this.status == "DRAFT") ||
          this.reviewCanEdit
        ) {
          let hasFile = this.$refs.basicForm.haveAttachFile();
          if (hasFile || this.createByRobot) {
            this.$refs.basicForm
              .getFormData()
              .then((formData) => {
                formData.title = this.orderTitle;
                formData.isCommit = false;
                saveOrUpdate(formData)
                  .then((res) => {
                    resolve(true);
                  })
                  .catch((e) => {
                    reject(e);
                  });
              })
              .catch((e) => {
                if (this.reviewCanEdit && e == "未填写完整") {
                  this.$message.warning("请将“基本信息”填写完整！");
                }
                reject(e);
              });
          } else {
            this.$message.warning("请上传现场照片!");
          }
        } else {
          resolve(true);
        }
      });
    },
    //提交前检测(兴化)
    async submitBeforeXH(data) {
      //如果是起草节点;设备管理单位领导审核时，可修改基本信息
      return new Promise((resolve, reject) => {
        if (this.status == "DRAFT") {
          this.$refs.basicForm
            .getFormData()
            .then((formData) => {
              formData.title = this.orderTitle;
              formData.isCommit = false;
              saveOrUpdate(formData)
                .then((res) => {
                  resolve(true);
                })
                .catch((e) => {
                  reject(e);
                });
            })
            .catch((e) => {
              this.$message.warning("请将“基本信息”填写完整！");
              reject(e);
            });
        } else {
          resolve(true);
        }
      });
    },
    //工作流提交成功之后
    workFlowSuccess() {
      if (this.isChangeRouter) {
        this.isChangeRouter = false;
        this.changeRouter();
      } else {
        this.showFlowDialog = false;
        if (this.$refs.workFlow) {
          this.$refs.workFlow.getFlowInfo();
        }
        this.$utils.addOperateLog(this.formData.id, "审批-缺陷工单");
        this.$utils.updateStorage();
        this.$refs.basicForm.getDetails();
      }
    },
    changeFormData(val) {
      this.formData = val;
      this.status = val.status || "";
      if (!["rescue", "oneclass"].includes(this.formData.level)) {
        this.analysisConfig.itemArr.forEach((item) => {
          item.required = false;
        });
      }
      if (val.idInspectResultLog) {
        this.createByRobot = true;
      }
      if (val.patrolId) {
        this.getPatrolOrder(val.patrolId);
      }
    },
    //获取巡视工单
    getPatrolOrder(id) {
      getPatrolOrderList({ id: id }).then((res) => {
        this.patrolSetting.data = res.data.list;
      });
    },
    setOrderTitle(data) {
      if (!this.userInput) {
        this.orderTitle = data;
      }
    },
    setTypeId(typeId) {
      this.typeId = typeId;
    },
    //失去焦点
    loseFocus() {
      if (
        ["", null].includes(this.orderTitle) ||
        this.orderTitle.match(/^[ ]*$/)
      ) {
        if (this.$refs.basicForm.getTitle()) {
          this.$message.warning("标题不能为空，已为您自动生成标题！");
          this.orderTitle = this.$refs.basicForm.getTitle();
          this.showInput = false;
        } else {
          this.showInput = true;
        }
      } else {
        this.showInput = false;
      }
    },
    //编辑标题
    editTitle() {
      this.showInput = true;
      setTimeout(() => {
        this.$refs.mark.focus();
      }, 0);
    },
    //用户输入工单标题
    userInputTitle(val) {
      if (val) {
        this.userInput = true;
      } else {
        this.userInput = false;
      }
    },
    initUserInput(val) {
      this.userInput = val;
    },
    //缺陷历史,(当前工单设备的缺陷历史)
    getHistoryList(params, sortStr) {
      this.$set(
        this.tableSetting.searchObj.queryData,
        "equipmentName",
        this.formData.equipmentName
      );
      this.$set(
        this.tableSetting.searchObj.queryData,
        "equipmentId",
        this.formData.equipmentId
      );

      let form = { ...params };
      form.type = this.menuType;
      form.equipmentName = this.formData.equipmentName;
      form.equipmentId = this.formData.equipmentId;
      if (sortStr) {
        form.orders = sortStr;
      }
      getListNoPageApi(form)
        .then((res) => {
          let data = res.data || [];
          this.$set(this.tableSetting, "tableData", data);
        })
        .catch((e) => {
          this.$set(this.tableSetting, "tableData", []);
        });
    },
    //打印预览
    async toPrint() {
      let basic = await this.$refs.basicForm.getFormData(false);
      let dispatch = this.$refs.dispatch.getFormData();
      let insturn = await this.$refs.perform.getPerformData();
      let accept = this.$refs.acceptance.getFormData();
      let orderExecutePart = [];
      // insturn.forEach((item) => {
      //   item.orderExecutePart.forEach((i) => {
      //     i.outDispatch = item.outDispatch;
      //     i.context = item.context;
      //     orderExecutePart.push(i);
      //   });
      // });
      this.printData = {
        id: basic.id,
        code: basic.code,
        type: this.$store.getters["fineDirtDataName"](
          "order_defect_type",
          basic.type
        ),
        deptId: basic.deptName,
        equipmentCode: basic.equipmentCode,
        equipmentName: basic.equipmentName,
        model: basic.model,
        manufacturer: basic.manufacturer,
        equipmentLocation: basic.equipmentLocation,
        createTime: basic.createTime,
        desc: basic.desc,
        leader: dispatch.headName,
        createByName: basic.createByName,
        deptName: dispatch.workUnitName,
        time: insturn[0].factStartTime,
        context: dispatch.context,
        acceptName: accept.acceptorName,
        result: accept.result == 1 ? "通过" : "不通过",
        insturn: insturn,
        content:""
      };
      this.printData.workList =
        dispatch.orderDispatchWorkerList.length > 0
          ? dispatch.orderDispatchWorkerList.map((i) => i.workerName).join(",")
          : "";
      // setTimeout(() => {
      //   this.$print(this.$refs.printTable.$refs["sign-table--box"]);
      // }, 200);
      //this.showPrintReview = true;
      localStorage.setItem("print-review",JSON.stringify(this.printData));
      const { href } = this.$router.resolve({
        name: "defectOrderPrint",
      })
      window.open(href, "_blank")
    },
    //选择工作票类型
    selectTicketType(item) {
      let { id, code } = this.formData;
      let data = { orderId: id, orderCode: code };
      let routerForm = {
        val: JSON.stringify(data) || "",
        pageType: "orderAdd",
        ticketType: item.value,
      };
      this.goToDetails("workTicketProcessingDetails", routerForm);
    },
    goToDetails(name, queryData) {
      const { href } = this.$router.resolve({
        name: name,
        query: queryData,
      });
      window.open(href, "_blank");
    },
    //跳转到详情页
    goDetailPage(row, router, type) {
      const { href } = this.$router.resolve({
        name: router,
        query: {
          id: row ? row.id : "",
          pageType: type ? type : "",
        },
      });
      window.open(href, "_blank");
    },
    toChange() {
      let { id, code, major } = this.formData;
      let form = {
        pageType: "orderAddChange",
        orderId: id,
        orderCode: code,
        orderType: "defect",
        major: major,
      };
      let { href } = this.$router.resolve({
        name: "orderChangeDetails",
        query: form,
      });
      window.open(href, "_blank");
    },
    //检修申请
    toService() {
      let { id, code } = this.formData;
      let query = {
        id: "",
        pageType: "orderAdd",
        orderId: id,
        orderCode: code,
      };
      this.goToDetails("overhaulApplicationDetails", query);
    },
    //工单抽查
    closeCheckRecord() {
      this.showCheckRecord = false;
    },
    //导出执行信息
    exportExecute() {
      let path =
        "eam-service-order/orderExecute/exportExecuteInfo?orderId=" +
        this.formData.id;
      let fileName = `${this.formData.title}执行信息`;
      this.$utils.downloadFile(null, null, path);
    },
    //补录备品备件
    async supplement() {
      let insturn = await this.$refs.perform.getPerformData();
      this.exexuteInfo = insturn;
      this.showSpareParts = true;
    },
    //执行补录操作
    async doSparePart() {
      let data = this.$refs.spareParts.getFormData();
      let res = await saveExecute(data);
      if (res.code == 200) {
        this.$message.success(res.description);
      }
      this.showSpareParts = false;
    },
  },
};
</script>
<style lang="less" scoped>
.defectOrderDetails {
  .tipText {
    color: #cecece;
    text-align: left;
  }
  background-color: #ffffff;
  .TitleImg {
    margin-right: 2px;
    font-size: 22px;
  }
  .titleText {
    display: inline-block;
    height: 30px;
    max-width: 800px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    margin-right: 5px;
  }
  .el-link {
    margin-bottom: 5px;
  }

  .orderTitle {
    height: 60px;
    margin: 0 0 10px 0;
    .name {
      font-size: 18px;
      padding: 0 10px;
      height: 40px;
      font-weight: bold;
      line-height: 40px;
      text-align: left;
      padding: 0 10px;
    }
    .name-input {
      width: 600px;
      height: 40px;
      line-height: 40px;
    }
    .remindColor {
      /deep/.el-input__inner {
        border: 1px solid red !important;
      }
    }
  }
  /deep/.selectContent .el-input--suffix .el-input__inner {
    min-height: 32px !important;
  }
}
.ticketType {
  position: absolute;
  right: 215px;
  top: 115px;
  z-index: 9999;
}
.ticketTypeBtn {
  width: 150px;
  height: 300px;
  background-color: rosybrown;
}
.attachConten {
  display: flex;
  flex-flow: wrap nowrap;
  .attachTitle {
    width: 143px;
    text-align: right;
    padding-right: 10px;
    font-size: 14px;
    color: #606266;
  }
  .tebleDiv {
    width: 100%;
  }
}
</style>
